package cn.hl.hm.controller;

import cn.hl.hm.constants.ModelConfig;
import cn.hl.hm.constants.PayMethod;
import cn.hl.hm.constants.ScanPayCode;
import cn.hl.hm.dao.DriverMapper;
import cn.hl.hm.dao.RoadFeeMapper;
import cn.hl.hm.dao.STSPriceMapper;
import cn.hl.hm.entity.*;
import cn.hl.hm.service.*;
import cn.hl.hm.util.*;
import cn.hl.hm.util.wxjs.BizOrder;
import cn.hl.hm.util.wxjs.CommonUtil;
import cn.hl.hm.util.wxjs.PayInfo;
import com.alipay.demo.trade.model.TradeStatus;
import com.alipay.demo.trade.model.result.AlipayF2FPayResult;
import com.alipay.demo.trade.model.result.AlipayF2FPrecreateResult;
import com.aliyuncs.dysmsapi.model.v20170525.SendSmsRequest;
import com.aliyuncs.exceptions.ClientException;
import com.tencent.business.ScanPayBusiness;
import com.tencent.listener.DefaultScanPayBusinessResultListener;
import com.tencent.protocol.pay_protocol.ScanPayReqData;
import com.tencent.protocol.pay_protocol.ScanPayResData;
import com.vizhuo.utils.DateUtil;
import com.zfb.ZfbMain;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import smsClient.TestSDKClient;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.UnsupportedEncodingException;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 
 * @author 大和 收费系统订单
 *
 */
@Controller
@RequestMapping("/roadFeeController")
public class RoadFeeController {
	private static final Logger logger = LoggerFactory.getLogger(RoadFeeController.class);
	@Autowired
	RoadFeeService roadFeeService;
	@Autowired
	RechargeRecoardService rechargeRecoardService;
	@Autowired
	private BeanPicUtil beanPicUtil;

	@Autowired
	private DriverService driverService;

	@Autowired
	private DriverMapper driverMapper;

	@Autowired
	private RoadFeeMapper roadFeeMapper;

	@Autowired
	RebateService rebateService;

	@Autowired
	private STSPriceMapper stsPriceMapper;

	@Autowired
	private DriverOwnInfoService driverOwnInfoService;
	@Autowired
	private PushToAppIService pushToAppIService;

	@RequestMapping(value = "/create", method = RequestMethod.POST)
	public String create(@RequestParam String serialNumber, @RequestParam String carFeeType,
			// @RequestParam String carGeneralType,
			@RequestParam String carNarrowType, @RequestParam String payType,
			// @RequestParam String licenseNumber,
			@RequestParam String totalPrice,

			String platNumPic, String platNum, String remark, String freeReason, String driverId, String feeStandard,
			String collectorName,

			String isFullLoad, String isSecurity, // 0 收 1 不
			BigDecimal securityFee,

			HttpServletRequest request, HttpServletResponse response) {
		logger.info("订单---订单创建---roadFeeController/create");
		if (isSecurity.equals("1") || isSecurity.equals("0")) {

		} else {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}
		if (securityFee.compareTo(new BigDecimal(0)) < 0) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}

		if (isSecurity.equals("0") && securityFee.compareTo(new BigDecimal(0)) <= 0) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}

		if (payType.equals(PayMethod.ROAD_BALANCE.getCode()) && StringUtils.isBlank(driverId)) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}

		if (payType.equals(PayMethod.ROAD_BALANCE.getCode()) && StringUtils.isBlank(driverId)) {
			Result.ok(null, InfoCode.PARAM_ERROR, response);
			return null;
		}

		if (carFeeType.equals("正常车") || carFeeType.equals("市场车")) {
			if (StringUtils.isBlank(feeStandard)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			} else if (StringUtils.isBlank(carNarrowType)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			} else if (StringUtils.isBlank(payType)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

		} else if (carFeeType.equals("免费车")) {
			if (StringUtils.isBlank(freeReason)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}
		} else if (carFeeType.equals("其他车")) {
			if (StringUtils.isBlank(carNarrowType)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			} else if (StringUtils.isBlank(payType)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			} else if (StringUtils.isBlank(feeStandard)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}
		}
		RoadFee rf = new RoadFee();
		try {
			Driver driver=null;
			if (StringUtils.isNotBlank(driverId)) {
				rf.setDriverId(Integer.parseInt(driverId));
				driver=driverService.selectByPrimaryKey(rf.getDriverId());
				if (driver!=null) {
					if(driver.getNoloadFree().equals(1)){
						rf.setSecurityFee(new BigDecimal(0));
						rf.setIsSecurity("1");
					}else{
						rf.setSecurityFee(securityFee);
						rf.setIsSecurity(isSecurity);
					}
				}else {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			}else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}
			rf.setCreateTime(new Date());
			rf.setRemark(remark);
			rf.setReciviceMoneySerialNumber(serialNumber);
			rf.setCarFeeType(carFeeType);
			rf.setCarNarrowType(carNarrowType);
			rf.setTotalPrice(new BigDecimal(totalPrice));
			rf.setPayType(payType);
			rf.setOrderStatus("1");// 未支付
			rf.setIsFullLoad(isFullLoad);
			if (carFeeType.equals("免费车")) {
				rf.setOrderStatus("2");
			}
			if (StringUtils.isNotBlank(feeStandard)) {
				rf.setFeeStandard(Integer.parseInt(feeStandard));
			}
			rf.setPayPrice(new BigDecimal(totalPrice));
			// rf.setOrderCode(OrderUtil.getInstance().getRoadFeeOrderCode());
			// rf.setDriverLicense(licenseNumber);
			rf.setPlateNumberPic(platNumPic);
			rf.setPlateNumber(platNum);

			RoadFee cutUrl = beanPicUtil.cutUrl(rf);

			String generateOrderCode = roadFeeService.generateOrderCode(carNarrowType);
			if (StringUtils.isBlank(generateOrderCode)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

			rf.setOrderCode(generateOrderCode);

			rf.setCollectorName(collectorName);
			int add = roadFeeService.add(cutUrl);
			if (add > 0) {
				driver.setNoloadFree(0);
				driver.setIsSecurity("0");
				driver.setFreeTime(null);
				driverService.updateByPrimaryKeySelective(driver);
				// pay
				Result.ok(rf, InfoCode.SUCCESS, response);
				return null;
			} else {
				Result.ok(rf, InfoCode.FAILURE, response);
				return null;
			}
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(rf, InfoCode.FAILURE, response);
		}
		Result.ok(rf, InfoCode.SUCCESS, response);
		return null;

	}

	/**
	 * @Title: roadFeeInfo @Description: 訂單列表、詳細 @date: 2017年4月5日 @author:大和 @param
	 *         roadFee @param pageId @param pageCount @param request @param
	 *         response @return String @throws
	 */
	@RequestMapping(value = "/roadFeeInfo", method = RequestMethod.POST)
	public String roadFeeInfo(RoadFee roadFee, @RequestParam Integer pageId, @RequestParam Integer pageCount,
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("园区收费/订单---收费列表[配载费管理]/订单列表---roadFeeController/roadFeeInfo");

		try {
			if (StringUtils.isNotBlank(roadFee.getBeString())) {
				if (StringUtils.isBlank(roadFee.getEndString())) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			}
			if (StringUtils.isNotBlank(roadFee.getEndString())) {
				if (StringUtils.isBlank(roadFee.getBeString())) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);

				}
			}

			if (StringUtils.isNotBlank(roadFee.getBeString()) && StringUtils.isNotBlank(roadFee.getEndString())) {
				if (roadFee.getBeString().trim().equals("''")) {

				} else if (roadFee.getEndString().trim().equals("''")) {

				} else if (roadFee.getBeString().trim().equals("\"\"")) {

				} else if (roadFee.getEndString().trim().equals("\"\"")) {

				} else {
					roadFee.setBeString(roadFee.getBeString().trim() + ":00:00");
					roadFee.setEndString(roadFee.getEndString().trim() + ":59:59");
				}

			}
			AppPager handle = AppPager.handle(pageId, pageCount);
			roadFee.setPageId(handle.getPageId());
			roadFee.setPageCount(handle.getPageCount());

			List<RoadFee> selectPageList = roadFeeService.selectPageList(roadFee);

			if (selectPageList != null && selectPageList.size() > 0) {
				List<RoadFee> resList = new ArrayList<RoadFee>();
				for (RoadFee orderInfo2 : selectPageList) {

					RoadFee modifyUrl = beanPicUtil.modifyUrl(orderInfo2);

					resList.add(modifyUrl);
				}
				/*
				 * if(modifyUrl.getFeeStandard()!=null){ // // STSPrice selectByPrimaryKey =
				 * stsPriceMapper.selectByPrimaryKey(modifyUrl.getFeeStandard()); //
				 * modifyUrl.setStsPrice(selectByPrimaryKey); }
				 * 
				 * 
				 */
				OrderPO calculateOrder = OrderPO.calculateOrder(resList);
				Map<String, Object> resultMap = new LinkedHashMap<>();
				resultMap.put("orderCount", calculateOrder);
				resultMap.put("orderList", resList);

				Result.ok(resultMap, InfoCode.SUCCESS, response);
				return null;
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	/**
	 * @Title: roadFeeInfo @Description: 訂單列表、詳細 @date: 2017年4月5日 @author:大和 @param
	 *         roadFee @param pageId @param pageCount @param request @param
	 *         response @return String @throws
	 */
	@RequestMapping(value = "/roadFeeInfoBack", method = RequestMethod.POST)
	public String roadFeeInfoBack(RoadFee roadFee, @RequestParam Integer pageId, @RequestParam Integer pageCount,
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("园区收费/订单---收费列表[配载费管理]/订单列表---roadFeeController/roadFeeInfo");

		try {
			if (StringUtils.isNotBlank(roadFee.getBeString())) {
				if (StringUtils.isBlank(roadFee.getEndString())) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			}
			if (StringUtils.isNotBlank(roadFee.getEndString())) {
				if (StringUtils.isBlank(roadFee.getBeString())) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);

				}
			}

			if (StringUtils.isNotBlank(roadFee.getBeString()) && StringUtils.isNotBlank(roadFee.getEndString())) {
				if (roadFee.getBeString().trim().equals("''")) {

				} else if (roadFee.getEndString().trim().equals("''")) {

				} else if (roadFee.getBeString().trim().equals("\"\"")) {

				} else if (roadFee.getEndString().trim().equals("\"\"")) {

				} else {
					roadFee.setBeString(roadFee.getBeString().trim() + ":00:00");
					roadFee.setEndString(roadFee.getEndString().trim() + ":59:59");
				}

			}
			AppPager handle = AppPager.handle(pageId, pageCount);
			roadFee.setPageId(handle.getPageId());
			roadFee.setPageCount(handle.getPageCount());

			List<RoadFee> selectPageList = roadFeeService.selectPageList(roadFee);

			if (selectPageList != null && selectPageList.size() > 0) {
				// List<RoadFee> resList = new ArrayList<RoadFee>();
				// for (RoadFee orderInfo2 : selectPageList) {
				//
				// RoadFee modifyUrl = beanPicUtil.modifyUrl(orderInfo2);
				//
				// resList.add(modifyUrl);
				// }
				/*
				 * if(modifyUrl.getFeeStandard()!=null){ // // STSPrice selectByPrimaryKey =
				 * stsPriceMapper.selectByPrimaryKey(modifyUrl.getFeeStandard()); //
				 * modifyUrl.setStsPrice(selectByPrimaryKey); }
				 * 
				 * 
				 */
				// OrderPO calculateOrder = OrderPO.calculateOrder(resList);
				Map<String, Object> resultMap = new LinkedHashMap<>();
				// resultMap.put("orderCount", calculateOrder);
				resultMap.put("orderList", selectPageList);
				roadFee.setPageId(null);
				roadFee.setPageCount(null);
				resultMap.put("num", roadFeeMapper.selectRoadFeeNum(roadFee));
				resultMap.put("allRoadFee", roadFeeMapper.selectAllRoadFee(roadFee));
				Result.ok(resultMap, InfoCode.SUCCESS, response);
				return null;
			} else {
				Result.ok(null, InfoCode.SUCCESS, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	/**
	 * @Description: 扫码支付（扫用户条形码 ） 支付宝、微信 注意◆微信 支付金额>500元的交易需要验证用户支付密码 ◆
	 *               用户账号每天最多有5笔交易可以免密，超过后需要验证密码
	 * @date: 2017年3月20日
	 * @author:大和
	 */
	@RequestMapping(value = "/scanUserPay", method = RequestMethod.POST)
	public String orderPay(@RequestParam String authCode, @RequestParam String clientIp, @RequestParam String orderCode,
			@RequestParam String serialNumber,

			HttpServletRequest request, HttpServletResponse response) {
		logger.info("资金---扫用户码支付（微信+支付宝）---roadFeeController/scanUserPay");
		try {
			RoadFee roadFee = new RoadFee();
			roadFee.setOrderCode(orderCode);
			List<RoadFee> selectPageList = roadFeeService.selectPageList(roadFee);
			// 解決paramError
			if (selectPageList != null && selectPageList.size() > 0) {
				if (selectPageList.size() != 1) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			} else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}
			RoadFee orderInfoResult = selectPageList.get(0);

			if (!orderInfoResult.getOrderStatus().equals("1")) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

			String payMethod = ScanPayCode.getPayMethod(authCode);
			if (StringUtils.isBlank(payMethod)) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			} else {
				SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
				String format = "";
				System.out.println(format);
				Date payTime = orderInfoResult.getPayTime();
				if (payTime != null) {
					format = sdf.format(payTime);

				}
				if (payMethod.equals(PayMethod.ROAD_WX_SCAN_USER.getCode())) {

					String dateTime = new SimpleDateFormat("yyyyMMddHHmmss").format(new Date());

					// 订单失效时间，这个每个商户有自己的过期原则，我这里设置的是10天后过期
					SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyyMMddHHmmss");
					Calendar c = Calendar.getInstance();
					c.setTime(new Date());
					c.add(Calendar.DAY_OF_MONTH, 10);
					String expireTime = simpleDateFormat.format(c.getTime());
					// 共9个必填参数
					ScanPayReqData scanPayReqData = new ScanPayReqData(authCode, "华凌-配载费", "刷卡支付", orderCode,
							NumberUtils.y2f(orderInfoResult.getPayPrice() + ""), serialNumber, // 非必填
							clientIp, dateTime, expireTime, "");
					DefaultScanPayBusinessResultListener listener = new DefaultScanPayBusinessResultListener();
					// 去支付
					new ScanPayBusiness().run(scanPayReqData, listener);
					String result = listener.getResult();
					logger.info("--刷卡支付监听器 返回结果：" + result);
					ScanPayResData resData = listener.getResData();
					if (result.equals("on_success")) {
						// 更改订单支付状态
						RoadFee update = new RoadFee();
						update.setId(orderInfoResult.getId());
						if (StringUtils.isNotBlank(resData.getTime_end())) {
							Date string2Date = DateUtil.string2Date(resData.getTime_end(), "yyyyMMddHHmmss");
							update.setPayTime(string2Date);

						}
						update.setOrderStatus("2");
						update.setPayTransNo(resData.getTransaction_id());
						update.setPaymentNo(resData.getOpenid());
						update.setSigns(resData.getSign());
						update.setPayType(PayMethod.ROAD_WX_SCAN_USER.getCode());
						update.setPayMsg(resData.toString());
						update.setReciviceMoneySerialNumber(serialNumber);
						int updateByPrimaryKey = roadFeeService.update(update);
						if (updateByPrimaryKey > 0) {
							Driver selectDriver = driverMapper.selectByPrimaryKey(orderInfoResult.getDriverId());
							if (selectDriver != null) {
								BigDecimal remainCash = selectDriver.getRemainCash();
								String driverPhone = selectDriver.getDriverAccount();

//								TestSDKClient.testSendSMSE(driverPhone,
//										"【华凌叮当到】温馨提示您，" + orderInfoResult.getPlateNumber() + "车辆在" + format
//												+ "支付华凌园区配载费" + orderInfoResult.getTotalPrice() + "元整，账户余额" + remainCash
//												+ "元【华凌叮当到：400-998-3903】");
//								SendSmsRequest smsRequest = new SendSmsRequest();
//								smsRequest.setTemplateParam("{\"plateNumber\":\""+orderInfoResult.getPlateNumber()+"\",\"totalPrice\":\""+orderInfoResult.getTotalPrice()+"\",\"remainCash\":\""+remainCash+"\",\"currentDate\":\""+format+"\"}");
//							    String sendSmsByAli = TestSDKClient.sendSmsByAli("SMS_110555059",smsRequest,driverPhone,"华凌叮当到");

								pzfPayPush(selectDriver.getId(),orderInfoResult,selectDriver,orderInfoResult.getTotalPrice(), format);
//								logger.info("....结束发送短信...driverPhone " +sendSmsByAli);
							}

							Result.ok(null, InfoCode.SUCCESS, response);
							return null;
						} else {
							Result.ok(null, InfoCode.PAY_OK_UPDATE_ERROR, response);
							return null;
						}
					} else {
						Result.ok(null, InfoCode.FAILURE, response);
						return null;
					}
				} else if (payMethod.equals(PayMethod.ROAD_ZFB_SCAN_USER.getCode())) {
					AlipayF2FPayResult result = new ZfbMain().test_trade_pay(orderInfoResult, authCode);
					logger.info(result.toString());
					TradeStatus tradeStatus = result.getTradeStatus();
					if (tradeStatus.toString().equals("SUCCESS")) {
						// 更改订单支付状态
						RoadFee update = new RoadFee();
						update.setId(orderInfoResult.getId());
						update.setPayTime(result.getResponse().getGmtPayment());
						update.setOrderStatus("2");
						update.setPayTransNo(result.getResponse().getTradeNo());
						update.setPaymentNo(result.getResponse().getOpenId());
						update.setPayType(PayMethod.ROAD_ZFB_SCAN_USER.getCode());
						update.setPayMsg(result.getResponse().getBody());
						update.setReciviceMoneySerialNumber(serialNumber);
						int updateByPrimaryKey = roadFeeService.update(update);
						if (updateByPrimaryKey > 0) {

							Driver selectDriver = driverMapper.selectByPrimaryKey(orderInfoResult.getDriverId());
							if (selectDriver != null) {
								BigDecimal remainCash = selectDriver.getRemainCash();
								String driverPhone = selectDriver.getDriverAccount();
								logger.info("....开始发送短信...driverPhone " + driverPhone + "  remainCash " + remainCash);
//								TestSDKClient.testSendSMSE(driverPhone,
//										"【华凌叮当到】温馨提示您，" + orderInfoResult.getPlateNumber() + "车辆在" + format
//												+ "支付华凌园区配载费" + orderInfoResult.getTotalPrice() + "元整，账户余额" + remainCash
//												+ "元【华凌叮当到：400-998-3903】");
//								SendSmsRequest smsRequest = new SendSmsRequest();
//								smsRequest.setTemplateParam("{\"plateNumber\":\""+orderInfoResult.getPlateNumber()+"\",\"totalPrice\":\""+orderInfoResult.getTotalPrice()+"\",\"remainCash\":\""+remainCash+"\",\"currentDate\":\""+format+"\"}");
//							    String sendSmsByAli = TestSDKClient.sendSmsByAli("SMS_110555059",smsRequest,driverPhone,"华凌叮当到");
								pzfPayPush(selectDriver.getId(), orderInfoResult, selectDriver,orderInfoResult.getTotalPrice() , format);
//								logger.info("....结束发送短信...driverPhone " +sendSmsByAli);

							}

							Result.ok(null, InfoCode.SUCCESS, response);
							return null;
						} else {
							Result.ok(null, InfoCode.PAY_OK_UPDATE_ERROR, response);
							return null;
						}
					} else {
						Result.ok(null, InfoCode.FAILURE, response);
						return null;
					}

				} else {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	/**
	 * @Title: balancePay @Description: 余額支付 @date: 2017年4月5日 @author:大和 @param
	 *         driverId @param orderCode @param request @param response @return
	 *         String @throws
	 */
	@RequestMapping(value = "/balancePay", method = RequestMethod.POST)
	public String balancePay(@RequestParam Integer driverId, @RequestParam String orderCode,
			@RequestParam BigDecimal driverRemainCash, // 司机余额
			@RequestParam BigDecimal driverTotalPrice, // 总额 未打折
			@RequestParam BigDecimal driverPayPrice, // 支付金额 折后
			Integer discountId, // 折扣id
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("资金---订单余额支付---roadFeeController/balancePay");
		try {
			RoadFee roadFee = new RoadFee();
			roadFee.setOrderCode(orderCode);
			List<RoadFee> selectPageList = roadFeeService.selectPageList(roadFee);
			// 解決paramError
			if (selectPageList != null && selectPageList.size() > 0) {
				if (selectPageList.size() != 1) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					logger.info("支付失败，无此订单"+orderCode);
					return null;
				}
				// 1.待付款
				RoadFee orderInfoResult = selectPageList.get(0);
				if (!orderInfoResult.getOrderStatus().equals("1")) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					logger.info("支付失败，订单状态异常，订单号："+orderCode);
					return null;
				}
				Driver param = new Driver();
				param.setId(driverId);
				List<Driver> selectDriver = driverService.selectDriver(param);
				if (selectDriver != null && selectDriver.size() > 0) {
					Driver driver = selectDriver.get(0);
					BigDecimal remainCash = driver.getRemainCash();// 司机余额 包含待提现与待扣减
					if (remainCash == null) {
						Result.ok(null, InfoCode.DRIVER_BALANCE_ERROR, response);
						logger.info("支付失败，司机余额不足，订单号："+orderCode);
						return null;
					}
					Integer rows=roadFeeService.selectPayTimeBefore20MINUTE(driver.getId(),orderInfoResult.getPlateNumber());
					if (rows!=null && rows==0) {
						Result.ok(null, InfoCode.DRIVER_PAY_RESTRICTION_ERROR, response);
						logger.info("支付失败，订单2小时内不允许多次支付，订单号："+orderCode);
						return null;
					}
					//获取司机可用余额
					DriverAmountInfo selectDriverHistory = driverService.selectDriverHistory(driver.getId());
					if (driver.getWithdrawCash() != null && driver.getWithdrawCash().compareTo(new BigDecimal(0)) > 0) {
						BigDecimal giveCash = selectDriverHistory.getGiveCash();
						BigDecimal subedRewardCash = selectDriverHistory.getSubedRewardCash();
						BigDecimal subtract = giveCash.subtract(subedRewardCash);
						BigDecimal remainCashReal2 = driver.getRemainCash().subtract(driver.getWithdrawCash())
								.subtract(subtract);
						driver.setRemainCash(remainCashReal2);
						logger.info("当前提现金额" + driver.getWithdrawCash() + "总奖励金额" + giveCash + "已扣减奖励金额"
								+ subedRewardCash + "应扣减奖励金额" + subtract);
					}
					// 判断余额是否相同
					if (driver.getRemainCash() != null) {
						if (driver.getRemainCash().compareTo(driverRemainCash) != 0) {
							Result.ok(null, InfoCode.PARAM_ERROR, response);
							logger.info("支付失败，司机余额不匹配，订单号："+orderCode);
							return null;
						}

					}

					// 判断余额和支付金额
					// if(remainCash.subtract(driver.getWithdrawCash()).compareTo(orderInfoResult.getPayPrice())<0){
					// Result.ok(null, InfoCode.DRIVER_BALANCE_ERROR, response);
					// return null;
					// }
					// 2017-10-26
					if (driver.getRemainCash().compareTo(orderInfoResult.getTotalPrice()) < 0) {
						Result.ok(null, InfoCode.DRIVER_BALANCE_ERROR, response);
						logger.info("支付失败，司机余额不足，订单号："+orderCode);
						return null;
					}

					// 根据id出这条数据
					if (discountId != null) {
						Rebate rebateInfo = rebateService.selectRebate(discountId);
						if (rebateInfo != null) {

							// 折扣转成小数（例如0.9）
							double zhe = Double.valueOf(rebateInfo.getRebate().toString());
							// double转成BigDecimal
							BigDecimal z = new BigDecimal(Double.toString(zhe));

							BigDecimal result = driverTotalPrice.multiply(z);// 相乘结果
							result = result.setScale(2, RoundingMode.HALF_UP);
							if (result.compareTo(new BigDecimal(0.01)) < 0) {
								result = new BigDecimal(0.01);
							}
							logger.info("折前" + driverTotalPrice + "折后" + result);
							if (result.compareTo(driverPayPrice) != 0) {// 前后约定保留两位
								Result.ok(null, InfoCode.PARAM_ERROR, response);
								logger.info("支付失败，优惠金额和支付金额不匹配，订单号："+orderCode);
								return null;
							}

						}
					}

					driver.setRemainCash(remainCash.subtract(driverPayPrice));
					int updateDriver = driverService.updateDriver(driver);
					if (updateDriver > 0) {
						RoadFee updateParam = new RoadFee();
						updateParam.setOrderStatus("2");
						updateParam.setPayTime(new Date());
						updateParam.setPayType(PayMethod.ROAD_BALANCE.getCode());
						updateParam.setId(orderInfoResult.getId());
						if (discountId != null) {
							updateParam.setDiscountId(discountId);// 打折id
						}

						updateParam.setTotalPrice(driverTotalPrice);
						updateParam.setPayPrice(driverPayPrice);
						updateParam.setRemainFavourPrice(driverTotalPrice.subtract(driverPayPrice));
						int update = roadFeeService.update(updateParam);
						if (update > 0) {
							// 在此记录余额消费，保存在recharge_recoard 中。
							RechargeRecoard rr = new RechargeRecoard();
							rr.setOperType(2);// 消费
							rr.setStatus("2"); // 设置消费状态 2 成功
							rr.setOrderCode(orderCode);
							rr.setCreateTime(new Date());
							rr.setDriverId(driverId);
							rr.setRemainCash(driver.getRemainCash());
							rr.setUserphone(driver.getDriverAccount());
							rr.setAmount(driverPayPrice);
							rr.setType(6);
							int addRechargeRecoard = rechargeRecoardService.addRechargeRecoard(rr);
							if (addRechargeRecoard > 0) {

								if (orderInfoResult.getIsSecurity().equals("0")
										&& orderInfoResult.getSecurityFee().compareTo(new BigDecimal(0)) > 0) {
									BigDecimal remain = driver.getRemainCash();
									if (remain.compareTo(orderInfoResult.getSecurityFee()) >= 0) {
										// 扣减余额
										driver.setRemainCash(remain.subtract(orderInfoResult.getSecurityFee()));
										int update1 = driverService.updateDriver(driver);
										if (update1 > 0) {
											RoadFee updateRoadFeeSecurity = new RoadFee();
											updateRoadFeeSecurity.setSecurityType("2");// 1 未付 2余额已付 3现金已付
											updateRoadFeeSecurity.setId(orderInfoResult.getId());
											int update2 = roadFeeService.update(updateRoadFeeSecurity);
											if (update2 > 0) {
												RechargeRecoard rr2 = new RechargeRecoard();
												rr2.setOperType(5);// 保全金
												rr2.setStatus("2"); // 设置消费状态 2 成功
												rr2.setOrderCode(orderCode);
												rr2.setCreateTime(new Date());
												rr2.setDriverId(driverId);
												rr2.setRemainCash(driver.getRemainCash());
												rr2.setUserphone(driver.getDriverAccount());
												rr2.setAmount(orderInfoResult.getSecurityFee());
												rr2.setType(6);// 1微信／2支付宝／3现金/4 现金 5 pos 6余额
												int add1 = rechargeRecoardService.addRechargeRecoard(rr2);
												if (add1 > 0) {
													Date date = new Date();
													SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
													String format = sdf.format(date);
													logger.info("...发送短信...driverAccount" + driver.getDriverAccount()
															+ "  消费");
													// TestSDKClient.testSendSMSE(driver.getDriverAccount(),
													// "【华凌叮当到】温馨提示您，"+orderInfoResult.getPlateNumber()+"车辆在"+format+"支付华凌园区配载费"+rr.getAmount()+"元整，保全金"+rr2.getAmount()+"元整,账户余额"+rr2.getRemainCash()+"元【华凌叮当到：400-998-3903】");
													// 2017-10-26新需求
													// TestSDKClient.testSendSMSE(driver.getDriverAccount(),
													// "【华凌叮当到】温馨提示您，收取的"+rr2.getAmount()+"元保全金已为"+orderInfoResult.getPlateNumber()+"车辆提供单次最高150万元的货运保障服务。运输中遇到货损超过2000元的事故，请于24小时内拨打华凌叮当到客服热线400-998-3903（10:00-19:00）、13139633665（全天24小时）报备事故。");
													BigDecimal add = rr.getAmount().add(rr2.getAmount());
//													TestSDKClient.testSendSMSE(driver.getDriverAccount(),"【华凌叮当到】温馨提示您，"+orderInfoResult.getPlateNumber()+"车辆支付华凌园区服务费"+add+"元整（含配载费）,账户余额"+driver.getRemainCash()+"元。华凌园区已经为您购买中国人保提供的货运保险服务，单次事故最高赔付150万元。运输中遇到货损超过2000元的事故，请及时拨打95518报案，保单号：PYAD201765500000000006。并于24小时内拨打华凌叮当到客服热线400-998-3903（10:00-19:00）、13139633665（全天24小时）报备事故，华凌物流将竭诚为您处理赔付事务。");



													pzfPayPush(driverId, orderInfoResult.getPlateNumber(), driver, add);
												}
											}
										}
									} else {
										// 现金支付
										RoadFee updateRoadFeeSecurity = new RoadFee();
										updateRoadFeeSecurity.setSecurityType("3");// 1 未付 2余额已付 3现金已付
										updateRoadFeeSecurity.setId(orderInfoResult.getId());
										int update2 = roadFeeService.update(updateRoadFeeSecurity);
										if (update2 > 0) {
											RechargeRecoard rr2 = new RechargeRecoard();
											rr2.setOperType(5);// 保全金
											rr2.setStatus("2"); // 设置消费状态 2 成功
											rr2.setOrderCode(orderCode);
											rr2.setCreateTime(new Date());
											rr2.setDriverId(driverId);
											rr2.setRemainCash(driver.getRemainCash());
											rr2.setUserphone(driver.getDriverAccount());
											rr2.setAmount(orderInfoResult.getSecurityFee());
											rr2.setType(4);// 1微信／2支付宝/4 现金 5 pos 6余额
											int add1 = rechargeRecoardService.addRechargeRecoard(rr2);
											if (add1 > 0) {
												// Date date = new Date();
												// SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
												// String format = sdf.format(date);
												logger.info(
														"...发送短信...driverAccount" + driver.getDriverAccount() + "  消费");
												// TestSDKClient.testSendSMSE(driver.getDriverAccount(),
												// "【华凌叮当到】温馨提示您，"+orderInfoResult.getPlateNumber()+"车辆在"+format+"支付华凌园区配载费"+rr.getAmount()+"元整，保全金"+rr2.getAmount()+"元整,账户余额"+rr2.getRemainCash()+"元【华凌叮当到：400-998-3903】");
												// 2017-10-26新需求
												BigDecimal add = rr.getAmount().add(rr2.getAmount());
//												//TestSDKClient.testSendSMSE(driver.getDriverAccount(),"【华凌叮当到】温馨提示您，"+orderInfoResult.getPlateNumber()+"车辆支付华凌园区服务费"+add+"元整（含配载费）,账户余额"+driver.getRemainCash()+"元。华凌园区已经为您购买中国人保提供的货运保险服务，单次事故最高赔付150万元。运输中遇到货损超过2000元的事故，请及时拨打95518报案，保单号：PYAD201765500000000006。并于24小时内拨打华凌叮当到客服热线400-998-3903（10:00-19:00）、13139633665（全天24小时）报备事故，华凌物流将竭诚为您处理赔付事务。");
//												SendSmsRequest smsRequest = new SendSmsRequest();
//												smsRequest.setTemplateParam("{\"plateNumber\":\""+orderInfoResult.getPlateNumber()+"\",\"payPrice\":\""+add+"\",\"remainCash\":\""+driver.getRemainCash()+"\"}");
//											    TestSDKClient.sendSmsByAli("SMS_110495048",smsRequest,driver.getDriverAccount(),"华凌叮当到");
												pzfPayPush(driverId, orderInfoResult.getPlateNumber(), driver, add);
											}
										}

									}
									// email
//									EmailUtil.sendEmail(orderInfoResult.getPlateNumber(),
//											new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()));

								} else {
									Date date = new Date();
									SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
									String format = sdf.format(date);
									logger.info("...发送短信...driverAccount" + driver.getDriverAccount() + "  消费");
//									TestSDKClient.testSendSMSE(driver.getDriverAccount(),
//											"【华凌叮当到】温馨提示您，" + orderInfoResult.getPlateNumber() + "车辆在" + format
//													+ "支付华凌园区配载费" + rr.getAmount() + "元整，账户余额" + rr.getRemainCash()
//													+ "元【华凌叮当到：400-998-3903】");
									pzfPayPush(driverId, orderInfoResult, driver,rr.getAmount() , format);

								}
								Result.ok(null, InfoCode.SUCCESS, response);
								return null;
							} else {
								Result.ok(null, InfoCode.PARAM_ERROR, response);
								return null;
							}
						} else {
							Result.ok(null, InfoCode.FAILURE, response);
							return null;
						}
					} else {
						Result.ok(null, InfoCode.FAILURE, response);
						return null;
					}

				} else {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			} else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	private void pzfPayPush(Integer driverId, RoadFee orderInfoResult, Driver driver,BigDecimal amount,String format) throws UnsupportedEncodingException, ClientException {
		SendSmsRequest smsRequest = new SendSmsRequest();
		smsRequest.setTemplateParam("{\"plateNumber\":\""+orderInfoResult.getPlateNumber()+"\",\"totalPrice\":\""+amount+"\",\"remainCash\":\""+driver.getRemainCash()+"\",\"currentDate\":\""+format+"\"}");
		TestSDKClient.sendSmsByAli("SMS_110555059",smsRequest,driver.getDriverAccount(),"华凌叮当到");
		Push push = new Push();
		push.setBizzType(Push.BizzTypeEnum.PZF.getName());
		push.setPtype(Push.PushTypeEnum.PZFPUSH5.getId());
		push.setPushoid("");
		push.setDisplayType("notification");// message:// 消息，通知：notification
		push.setOperationType(1);// 用户类型：1司机，2发货端
		push.setPushClient("driverPushClient");// 使用的推送Client
		push.setPushType("listcast");// unicast：单播 // listcast：列表
		push.setTokenStr(new String[]{driver.getDeviceToken()}); // 要发送手机的token
		// ios & android推送公共调用方法
		String content="温馨提示您，" + orderInfoResult.getPlateNumber() + "车辆在" + format
                + "支付华凌园区配载费" + amount + "元整，账户余额" +driver.getRemainCash()
                + "元【华凌叮当到：400-998-3903】";
		push.setContext(content);// 要发送的内容
		push.setTitle("配载费扣费成功"); // 发送的标题
		driverOwnInfoService.insertSelective(push.getContext(),driverId);
		pushToAppIService.pushCommon(push);
	}

	private void pzfPayPush(Integer driverId,String plateNumber,Driver driver, BigDecimal add) throws UnsupportedEncodingException, ClientException {
		SendSmsRequest smsRequest = new SendSmsRequest();
		smsRequest.setTemplateParam("{\"plateNumber\":\""+plateNumber+"\",\"payPrice\":\""+add+"\",\"remainCash\":\""+driver.getRemainCash()+"\"}");
		TestSDKClient.sendSmsByAli("SMS_110495048",smsRequest,driver.getDriverAccount(),"华凌叮当到");
		Push push = new Push();
		push.setBizzType(Push.BizzTypeEnum.PZF.getName());
		push.setPtype(Push.PushTypeEnum.PZFPUSH6.getId());
		push.setPushoid("");
		push.setDisplayType("notification");// message:// 消息，通知：notification
		push.setOperationType(1);// 用户类型：1司机，2发货端
		push.setPushClient("driverPushClient");// 使用的推送Client
		push.setPushType("listcast");// unicast：单播 // listcast：列表
		push.setTokenStr(new String[]{driver.getDeviceToken()}); // 要发送手机的token
		// ios & android推送公共调用方法
		String content="温馨提示您，"+plateNumber+"车辆支付华凌园区服务费"+add+"元整（含配载费）,账户余额"+driver.getRemainCash()+"元。华凌园区已经为您购买中国人保提供的货运保险服务，单次事故最高赔付150万元。运输中遇到货损超过2000元的事故，请及时拨打95518报案，保单号：PYAD201765500000000006。并于24小时内拨打华凌叮当到客服热线400-998-3903（10:00-19:00）、13139633665（全天24小时）报备事故，华凌物流将竭诚为您处理赔付事务。";
		push.setContext(content);// 要发送的内容
		push.setTitle("配载费含保全金扣费成功"); // 发送的标题
		driverOwnInfoService.insertSelective(push.getContext(),driverId);
		pushToAppIService.pushCommon(push);
	}

	@RequestMapping(value = "/cashPay", method = RequestMethod.POST)
	public String cashPay(@RequestParam String orderCode, HttpServletRequest request, HttpServletResponse response) {
		logger.info("资金---订单现金支付---roadFeeController/cashPay");
		try {
			RoadFee roadFee = new RoadFee();
			roadFee.setOrderCode(orderCode);
			List<RoadFee> selectPageList = roadFeeService.selectPageList(roadFee);
			// 解決paramError
			if (selectPageList != null && selectPageList.size() > 0) {
				if (selectPageList.size() != 1) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
				RoadFee orderInfoResult = selectPageList.get(0);

				if (!orderInfoResult.getOrderStatus().equals("1")) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
				Driver param = new Driver();
				param.setId(orderInfoResult.getDriverId());
				List<Driver> selectDriver = driverService.selectDriver(param);
				if (selectDriver == null || selectDriver.size() == 0) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
				Driver driver = selectDriver.get(0);
				Integer rows=roadFeeService.selectPayTimeBefore20MINUTE(driver.getId(),orderInfoResult.getPlateNumber());
				if (rows!=null && rows==0) {
					Result.ok(null, InfoCode.DRIVER_PAY_RESTRICTION_ERROR, response);
					return null;
				}
				RoadFee updateParam = new RoadFee();
				updateParam.setOrderStatus("2");
				updateParam.setPayTime(new Date());
				updateParam.setPayType(PayMethod.ROAD_CASH.getCode());
				updateParam.setId(orderInfoResult.getId());
				int update = roadFeeService.update(updateParam);
				if (update > 0) {
					if (orderInfoResult.getIsSecurity().equals("0")
							&& orderInfoResult.getSecurityFee().compareTo(new BigDecimal(0)) > 0) {
						// 现金支付
						RoadFee updateRoadFeeSecurity = new RoadFee();
						updateRoadFeeSecurity.setSecurityType("3");// 1 未付 2余额已付 3现金已付
						updateRoadFeeSecurity.setId(orderInfoResult.getId());
						int update2 = roadFeeService.update(updateRoadFeeSecurity);
						if (update2 > 0) {
						
							RechargeRecoard rr2 = new RechargeRecoard();
							rr2.setOperType(5);// 保全金
							rr2.setStatus("2"); // 设置消费状态 2 成功
							rr2.setOrderCode(orderCode);
							rr2.setCreateTime(new Date());
							rr2.setDriverId(orderInfoResult.getDriverId());
							rr2.setRemainCash(driver.getRemainCash());
							rr2.setUserphone(orderInfoResult.getDriverAccount());
							rr2.setAmount(orderInfoResult.getSecurityFee());
							rr2.setType(4);// 1微信／2支付宝/4 现金 5 pos 6余额
							rechargeRecoardService.addRechargeRecoard(rr2);

//							EmailUtil.sendEmail(orderInfoResult.getPlateNumber(),
//									new SimpleDateFormat("yyyy年MM月dd日 HH:mm:ss").format(new Date()));
							BigDecimal add = orderInfoResult.getTotalPrice().add(rr2.getAmount());
							//TestSDKClient.testSendSMSE(driver.getDriverAccount(),"【华凌叮当到】温馨提示您，"+orderInfoResult.getPlateNumber()+"车辆支付华凌园区服务费"+add+"元整（含配载费）,账户余额"+driver.getRemainCash()+"元。华凌园区已经为您购买中国人保提供的货运保险服务，单次事故最高赔付150万元。运输中遇到货损超过2000元的事故，请及时拨打95518报案，保单号：PYAD201765500000000006。并于24小时内拨打华凌叮当到客服热线400-998-3903（10:00-19:00）、13139633665（全天24小时）报备事故，华凌物流将竭诚为您处理赔付事务。");
//							SendSmsRequest smsRequest = new SendSmsRequest();
//							smsRequest.setTemplateParam("{\"plateNumber\":\""+orderInfoResult.getPlateNumber()+"\",\"payPrice\":\""+add+"\",\"remainCash\":\""+driver.getRemainCash()+"\"}");
//						    TestSDKClient.sendSmsByAli("SMS_110495048",smsRequest,driver.getDriverAccount(),"华凌叮当到");
							pzfPayPush(driver.getId(),orderInfoResult.getPlateNumber(),driver,add);
							Result.ok(null, InfoCode.SUCCESS, response);
							return null;

						} else {
							Result.ok(null, InfoCode.FAILURE, response);
							return null;
						}
					} else {
						Date date = new Date();
						SimpleDateFormat sdf = new SimpleDateFormat("yyyy年MM月dd日HH时mm分ss秒");
						String format = sdf.format(date);
						logger.info("...发送短信...driverAccount" + driver.getDriverAccount() + "  消费");
//						TestSDKClient.testSendSMSE(driver.getDriverAccount(),
//								"【华凌叮当到】温馨提示您，" + orderInfoResult.getPlateNumber() + "车辆在" + format + "支付华凌园区配载费"
//										+ orderInfoResult.getTotalPrice() + "元整，账户余额"
//										+ selectDriver.get(0).getRemainCash() + "元【华凌叮当到：400-998-3903】");
//						SendSmsRequest smsRequest = new SendSmsRequest();
//						smsRequest.setTemplateParam("{\"plateNumber\":\""+orderInfoResult.getPlateNumber()
//								+"\",\"totalPrice\":\""+orderInfoResult.getTotalPrice()+"\",\"remainCash\":\""
//								+driver.getRemainCash()+"\",\"currentDate\":\""+format+"\"}");
//					    TestSDKClient.sendSmsByAli("SMS_110555059",smsRequest,driver.getDriverAccount(),"华凌叮当到");
						pzfPayPush(driver.getId(), orderInfoResult, driver, orderInfoResult.getTotalPrice(), format);
						Result.ok(null, InfoCode.SUCCESS, response);
						return null;
					}

				} else {
					Result.ok(null, InfoCode.FAILURE, response);
					return null;
				}
			} else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	/**
	 * @Description: 支付宝扫码支付（扫商家 ） 支付宝
	 * @date: 2017年3月20日
	 * @author:大和
	 */
	@RequestMapping(value = "/scanMerPay", method = RequestMethod.POST)
	public String scanMerPay(@RequestParam String orderCode, @RequestParam String serialNumber,
			@RequestParam String type, // 1 微信 2 支付宝
			@RequestParam String clientIp, // ip地址
			HttpServletRequest request, HttpServletResponse response) {
		logger.info("资金---扫商家码支付（微信+支付宝）---roadFeeController/scanMerPay");
		try {

			RoadFee roadFee = new RoadFee();
			roadFee.setOrderCode(orderCode);
			List<RoadFee> selectPageList = roadFeeService.selectPageList(roadFee);
			// 解決paramError
			if (selectPageList != null && selectPageList.size() > 0) {
				if (selectPageList.size() != 1) {
					Result.ok(null, InfoCode.PARAM_ERROR, response);
					return null;
				}
			} else {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}
			RoadFee orderInfoResult = selectPageList.get(0);

			if (!orderInfoResult.getOrderStatus().equals("1")) {
				Result.ok(null, InfoCode.PARAM_ERROR, response);
				return null;
			}
			String preFixUrl = ModelConfig.QR_lONG_PIC_TEST;
			if (ModelConfig.status.equals("1")) {
				preFixUrl = ModelConfig.QR_LONG_PIC_ONLINE;
			}
			if (type.equals("1")) {
				orderInfoResult.setReciviceMoneySerialNumber(serialNumber);
				Map<String, String> wxScanMer = wxScanMer(orderInfoResult, clientIp);

				// 4 组装调用支付JSON参数
				String return_code = wxScanMer.get("return_code");
				String result_code = wxScanMer.get("result_code");

				if (return_code.equals("SUCCESS")) {
					String return_msg = wxScanMer.get("return_msg");
					if (!return_msg.equals("OK")) {
						logger.info("统一下单错误！");
						Result.ok(wxScanMer.toString(), InfoCode.FAILURE, response);
						return null;
					} else {
						if (result_code.equals("SUCCESS")) {
							logger.info("统一下单OK！");
							String codeUrl = wxScanMer.get("code_url");
							logger.info("code_url   :" + codeUrl);
							if (StringUtils.isNotBlank(codeUrl)) {
								String qr_url = "";
								if (ModelConfig.status.equalsIgnoreCase("0")) {
									qr_url = ModelConfig.QR_PIC_WINDOW;
								} else {
									qr_url = ModelConfig.QR_PIC_LINUX;

								}
								RoadFee update = new RoadFee();
								update.setId(orderInfoResult.getId());
								update.setReciviceMoneySerialNumber(serialNumber);
								update.setPayType(PayMethod.ROAD_WX_SCAN_MER.getCode());
								roadFeeService.update(update);
								String encode = QRCodeUtil.encodeDriverOrPay(codeUrl, qr_url, true);

								Result.ok(preFixUrl + encode, InfoCode.SUCCESS, response);
								return null;
							} else {
								Result.ok(wxScanMer.toString(), InfoCode.FAILURE, response);
								return null;
							}
						} else {
							logger.info("统一下单错误！");
							Result.ok(wxScanMer.toString(), InfoCode.FAILURE, response);
							return null;
						}

					}
				} else {
					logger.info("统一下单错误！");
					Result.ok(wxScanMer.toString(), InfoCode.FAILURE, response);
					return null;
				}

			} else {
				AlipayF2FPrecreateResult result = new ZfbMain().test_trade_precreate(orderInfoResult);
				if (result.getTradeStatus().toString().equalsIgnoreCase("SUCCESS")) {
					String url = preFixUrl + "qr-" + result.getResponse().getOutTradeNo() + ".png";
					RoadFee update = new RoadFee();
					update.setId(orderInfoResult.getId());
					update.setReciviceMoneySerialNumber(serialNumber);
					update.setPayType(PayMethod.ROAD_ZFB_SCAN_MER.getCode());
					roadFeeService.update(update);
					Result.ok(url, InfoCode.SUCCESS, response);
					return null;
				} else {
					Result.ok(result, InfoCode.FAILURE, response);
					return null;
				}
			}

		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
	}

	/**
	 * @Title: wxScanMer @Description: 微信扫码原生支付 @date: 2017年3月27日 @author:大和 @param
	 *         roadFee @param ip @return Map<String, String> @throws
	 */
	public Map<String, String> wxScanMer(RoadFee roadFee, String ip) {
		BizOrder bo = new BizOrder();
		// 组装订单数据
		bo.setId(roadFee.getId().toString());
		bo.setFeeAmount((int) (roadFee.getPayPrice().setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue() * 100));
		bo.setOrderCode(roadFee.getOrderCode());
		bo.setSeriNum(roadFee.getReciviceMoneySerialNumber());
		logger.info("订单总支付金额:" + bo.getFeeAmount());

		PayInfo pi = CommonUtil.createPayInfo(bo, ip, null);
		String sign;
		Map<String, String> map = null;
		try {
			sign = CommonUtil.getSign(pi);
			pi.setSign(sign);

			// 3 调用统一下单接口
			logger.info(CommonUtil.payInfoToXML(pi).replace("__", "_"));
			map = CommonUtil.httpsRequestToXML("https://api.mch.weixin.qq.com/pay/unifiedorder", "POST",
					CommonUtil.payInfoToXML(pi).replace("__", "_").replace("<![CDATA[", "").replace("]]>", ""));
			logger.info(map.toString());

		} catch (Exception e) {
			e.printStackTrace();
		}
		return map;

	}

	public static void main(String[] args) throws UnsupportedEncodingException, ClientException {
//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"plateNumber\":\""+1231231+"\",\"payPrice\":\""+1111+"\",\"remainCash\":\""+"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110495048",smsRequest,"15611570688","华凌叮当到");
//	    SendSmsRequest smsRequest2 = new SendSmsRequest();
//		smsRequest2.setTemplateParam("{\"code\":\""+888888888+"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110535050",smsRequest2,"15611570688","华凌叮当到");
//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"rechargeAmount\":\""+1+"\",\"giftAmount\":\""+2+"\",\"remainCash\":\""+3+"\",\"currentDate\":\""+4+"\"}");
//		TestSDKClient.sendSmsByAli("SMS_110495052",smsRequest,"15611570688","华凌叮当到");


//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"userAccount\":\""+123+"\",\"pass\":\""+456+"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110395052",smsRequest,"15611570688","华凌叮当到");
		
//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"driverAccount\":\""+123+"\",\"pass\":\""+34555+"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110435049",smsRequest,"15611570688","华凌叮当到");
		
//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"userAccount\":\""+12121212+"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110390043",smsRequest,"15611570688","华凌叮当到");
	    
//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"driverName\":\""+1+"\",\"payPrice\":\""+3+"\"}");
//		TestSDKClient.sendSmsByAli("SMS_110375056",smsRequest,"15611570688","华凌叮当到");
//		
//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"currentDate\":\""+new Date().toLocaleString()+"\",\"rechargeAmount\":\""+1+"\",\"remainCash\":\""+3+"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110585047",smsRequest,"15611570688","华凌叮当到");
//		
//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"currentDate\":\""+new Date().toLocaleString()+"\",\"rechargeAmount\":\""+1111+ "\",\"giftAmount\":\""+ 3333+ "\",\"remainCash\":\""+ 444 +"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110495051",smsRequest,"15611570688","华凌叮当到");


//		SendSmsRequest smsRequest = new SendSmsRequest();
//		smsRequest.setTemplateParam("{\"plateNumber\":\""+11+"\",\"totalPrice\":\""+22+"\",\"remainCash\":\""+33+"\",\"currentDate\":\""+44+"\"}");
//	    TestSDKClient.sendSmsByAli("SMS_110555059",smsRequest,"15611570688","华凌叮当到");

	}
	@RequestMapping(value = "/testOrderCode", method = RequestMethod.POST)
	public String testOrderCode(String type,
			HttpServletRequest request, HttpServletResponse response) {
		String generateOrderCode = null;
		try {
			 generateOrderCode = roadFeeService.generateOrderCode(type);
		} catch (Exception e) {
			e.printStackTrace();
			Result.ok(null, InfoCode.FAILURE, response);
			return null;
		}
		
		return generateOrderCode;
	}

}
